const jwt = require('jsonwebtoken');
const config = require('../config');

/**
 * JWT认证中间件
 * 验证请求中的JWT token
 */
function authMiddleware(req, res, next) {
  let token = null;

  // 从Authorization header中获取token
  const authHeader = req.headers.authorization;
  if (authHeader && authHeader.startsWith('Bearer ')) {
    token = authHeader.split(' ')[1];
  } 
  // 或从query参数中获取
  else if (req.query.token) {
    token = req.query.token;
  }

  if (!token) {
    return res.status(401).json({ 
      code: 401,
      message: '缺少认证token' 
    });
  }

  try {
    const decoded = jwt.verify(token, config.jwtSecret);
    req.user = decoded;
    console.log('[Auth] 用户认证成功:', req.user.username || req.user.userId);
    next();
  } catch (err) {
    console.error('[Auth] Token验证失败:', err.message);
    return res.status(401).json({ 
      code: 401,
      message: 'Token无效或已过期' 
    });
  }
}

module.exports = authMiddleware;

